package com.um.jdy.platform.financial.manager;


import com.um.jdy.common.finance.entity.dto.MerchantBillDTO;
import com.um.jdy.common.finance.entity.po.MerchantBill;
import com.um.jdy.common.finance.enums.FinancialEnum;
import com.um.jdy.common.finance.service.MerchantBillService;
import com.um.jdy.common.member.enums.MemberEnum;
import com.um.jdy.common.platform.code.PartnersCode;
import com.um.jdy.common.platform.entity.po.Merchant;
import com.um.jdy.common.platform.service.MerchantService;
import com.um.jdy.platform.financial.entity.vo.BillSummaryVO;
import com.um.jdy.platform.financial.entity.vo.MerchantBillItemVO;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.orm.params.ExportParams;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.orm.params.RangeParams;
import com.um.springboot.starter.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 管理类：商户流水表
 */
@Component
public class MerchantBillManager extends BaseManager<MerchantBillService> {

    @Autowired
    MerchantService merchantService;

    public Response<MerchantBill> addEntity(MerchantBillDTO dto) {
        if(merchantService.getEntity(dto.getPlatformMerchantId()) == null){
            return Response.failed(PartnersCode.PartnersNotExist);
        }

        MerchantBill entity = UMBeanUtils.copyBean(dto, MerchantBill.class);
        entity.setStatus(FinancialEnum.BillStatus.Effective.name());
        entity.setEvent(FinancialEnum.MerchantBillEvent.Artificial.name());
        entity.setNo(OrderUtil.getOrderNo());
        return Response.success(service.addEntity(entity));
    }

    /**
     * 分页查询运营商流水
     * @param pageParams
     * @return
     */
    public Response<Page<MerchantBillItemVO>> getBillPage(PageParams pageParams){
        Page<MerchantBillItemVO> page = new Page<>();
        page.setPageNo(pageParams.getPageNo());
        page.setPageSize(pageParams.getPageSize());

        pageParams.getCondition().put("a.com_id",getComId());
        pageParams.getCondition().put("mc.type",pageParams.getCondition().get("type"));
        pageParams.getCondition().remove("type");


        page = service.getCMSViewModelPageBySqlName(page,"get_merchant_bill_page","get_merchant_bill_count",MerchantBillItemVO.class,
                pageParams.getProperties(),pageParams.getValues(),pageParams.getRangeEntitys(),pageParams.getOrderNames(),pageParams.getSortOns());

        Integer balanceStart = this.getBillBalance(pageParams);

        //计算每笔的余额
        for(int index = 0;index < page.getResult().size();index ++){

            MerchantBillItemVO item = page.getResult().get(index);

            if(index > 0){
                balanceStart = page.getResult().get(index - 1).getBalance();
            }

            if(!StringUtil.equals(item.getStatus(), FinancialEnum.BillStatus.Invalided.name())){
                if(StringUtil.equals(FinancialEnum.IncomeOrExpend.Income.name(), item.getType())){
                    item.setBalance(balanceStart + item.getAmount());
                }else{
                    item.setBalance( balanceStart - item.getAmount());
                }
            }else{
                item.setBalance(balanceStart);
            }

        }

        page.setExtraData(this.getBillSummary(pageParams));

        return Response.success(page);
    }

    /**
     * 查询运营商余额
     * @param pageParams
     * @return
     */
    private Integer getBillBalance(PageParams pageParams){
        Integer amount = 0;
        String beginDate = "";
        Map<String, List<RangeParams>> rangeField = pageParams.getCustom().getRangeField();
        if(rangeField.containsKey("a.create_time")){
            List<RangeParams> listDateRange = rangeField.get("a.create_time");
            for(int index = 0;index < listDateRange.size();index ++){
                RangeParams item = listDateRange.get(index);
                if(item.getRange().equals("begin")){
                    beginDate = item.getValue();
                    break;
                }
            }
        }

        //开始日期之前的余额
        if(!beginDate.equals("")) {


            PageParams beginPageParams = new PageParams();
            beginPageParams.setCondition(pageParams.getCondition());


            MerchantBillItemVO entity = service.getCMSViewModelBySqlName("get_merchant_bill_before_date_balance",MerchantBillItemVO.class,
                    beginPageParams.getProperties(),beginPageParams.getValues(),beginPageParams.getRangeEntitys(),new Object[]{beginDate});
            if (entity != null) {
                amount = entity.getAmount();
            }

        }

        // 当前页码之前的
        if(pageParams.getPageNo() > 1) {
            PageParams beforePageParams = new PageParams();
            beforePageParams.setCondition(pageParams.getCondition());
            beforePageParams.setCustom(pageParams.getCustom());

            Integer limit = (pageParams.getPageNo() - 1) * pageParams.getPageSize();

            MerchantBillItemVO entity = service.getCMSViewModelBySqlName("get_merchant_bill_begin_balance",MerchantBillItemVO.class,
                    beforePageParams.getProperties(),beforePageParams.getValues(),beforePageParams.getRangeEntitys(),new Object[]{limit});
            if (entity != null) {
                amount = amount + entity.getAmount();
            }
        }

        return amount;
    }


    /**
     * 查询运营商流水统计结果
     *
     * @param pageParams
     * @return
     */
    private BillSummaryVO getBillSummary(PageParams pageParams) {

        BillSummaryVO entity = service.getCMSViewModelBySqlName("get_merchant_bill_summary",BillSummaryVO.class,
                pageParams.getProperties(),pageParams.getValues(),pageParams.getRangeEntitys());
        return entity;
    }


    /**
     * 导出运营商流水
     *
     * @param exportParams
     * @return
     */
    public Response exportBillPage(ExportParams exportParams){

        String userType = exportParams.getCondition().get("type");
        exportParams.getCondition().put("a.com_id",getComId());
        exportParams.getCondition().put("mc.type",userType);
        exportParams.getCondition().remove("type");

        List<MerchantBillItemVO> list = service.getCMSViewModelListBySqlName("get_merchant_bill_page",MerchantBillItemVO.class,exportParams.getProperties(),
                exportParams.getValues(),exportParams.getRangeEntitys(),exportParams.getOrderNames(),exportParams.getSortOns(),
                new Object[]{exportParams.getStart(),exportParams.getLimit()});

        PageParams pageParams = new PageParams();
        pageParams.setPageNo(exportParams.getPageNo());
        pageParams.setPageSize(exportParams.getPageSize());
        pageParams.setCondition(exportParams.getCondition());
        pageParams.setCustom(exportParams.getCustom());
        Integer balanceStart = this.getBillBalance(pageParams);

        //计算每笔的余额
        for(int index = 0;index < list.size();index ++){

            MerchantBillItemVO item =list.get(index);
            String type = item.getType();
            //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.US);
            //item.put("create_time", formatter.format((LocalDateTime)item.get("create_time")));

            if(index > 0){
                balanceStart = list.get(index - 1).getBalance();
            }


            if(!StringUtil.equals(item.getStatus(), FinancialEnum.BillStatus.Invalided.name())){
                if(StringUtil.equals(FinancialEnum.IncomeOrExpend.Income.name(), item.getType())){
                    item.setBalance(balanceStart + item.getAmount());
                }else{
                    item.setBalance(balanceStart - item.getAmount());
                }
            }else{
                item.setBalance(balanceStart);
            }

            if(type.equals(FinancialEnum.IncomeOrExpend.Expend.name())){
                item.setAmount(-item.getAmount());
            }
        }

        Map<String,String> mapFormat = new Hashtable<>();
        mapFormat.put("create_time","yyyy-MM-dd HH:mm:ss");
        mapFormat.put("balance","number");
        mapFormat.put("amount","number");

        String fileName = "Excel"+ DateUtil.getDateString(new Date(), "yyyyMMddHHmmss")+".xls";
        String path = service.getExportFilePath(fileName);
        String merchantName = "";
        if(userType.equals(MemberEnum.UserType.merchant.name())){
            merchantName = "运营商名称";
        }else if(userType.equals(MemberEnum.UserType.sharing.name())){
            merchantName = "商户名称";
        }
        List<String> columns = Arrays.asList(merchantName,"手机号码","收支类型","账单号","账单类型","交易金额","余额","状态","时间","订单编号","商户订单号","备注说明");
        List<String> properties = Arrays.asList("merchant_name","merchant_mobile","type","no","event","amount","balance","status","create_time","order_no","out_trade_no","remark");
        ExcelUtil.writeEntity(path, columns, list, properties, exportParams.getMapParam(), mapFormat, exportParams.getMapZero(),true);

        return Response.success(service.getDownFilePath(fileName));
    }
}
